package com.example.mydy.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.R;
import com.example.mydy.RewardDetailActivity;
import com.example.mydy.adapter.AvailableRewardAdapter;
import com.example.mydy.model.RewardTask;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 展示可接取的悬赏任务列表
 */
public class AvailableRewardsFragment extends Fragment implements AvailableRewardAdapter.OnRewardClickListener {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private TextView emptyView;
    private EditText searchEditText;
    private ChipGroup filterChipGroup;
    
    private AvailableRewardAdapter adapter;
    private List<RewardTask> allRewardTasks = new ArrayList<>();
    private List<RewardTask> filteredRewardTasks = new ArrayList<>();
    private MockDataManager mockDataManager;

    public AvailableRewardsFragment() {
        // 必需的空构造函数
    }

    public static AvailableRewardsFragment newInstance() {
        return new AvailableRewardsFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_available_rewards, container, false);
        
        mockDataManager = MockDataManager.getInstance();
        
        // 初始化视图
        initViews(view);
        
        // 加载数据
        loadRewardTasks();
        
        return view;
    }

    private void initViews(View view) {
        // 初始化SwipeRefreshLayout
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(this::loadRewardTasks);
        
        // 初始化RecyclerView
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        
        // 初始化空视图
        emptyView = view.findViewById(R.id.empty_view);
        
        // 初始化搜索框
        searchEditText = view.findViewById(R.id.search_edit_text);
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                filterRewardTasks();
            }
        });
        
        // 初始化过滤器
        filterChipGroup = view.findViewById(R.id.filter_chip_group);
        setupFilterChips();
        
        // 初始化适配器
        adapter = new AvailableRewardAdapter(filteredRewardTasks, this);
        recyclerView.setAdapter(adapter);
    }

    private void setupFilterChips() {
        // 添加常用任务类型作为过滤选项
        String[] categories = {"全部", "技术", "设计", "市场", "其他"};
        
        for (String category : categories) {
            Chip chip = new Chip(requireContext());
            chip.setText(category);
            chip.setCheckable(true);
            chip.setClickable(true);
            
            // 设置全部类别为默认选中
            if ("全部".equals(category)) {
                chip.setChecked(true);
            }
            
            chip.setOnCheckedChangeListener((buttonView, isChecked) -> {
                // 如果选中了"全部"，取消其他所有筛选条件
                if (isChecked && "全部".equals(category)) {
                    for (int i = 0; i < filterChipGroup.getChildCount(); i++) {
                        Chip otherChip = (Chip) filterChipGroup.getChildAt(i);
                        if (!otherChip.getText().equals("全部")) {
                            otherChip.setChecked(false);
                        }
                    }
                } 
                // 如果选中了其他类别，取消"全部"的选中状态
                else if (isChecked && !category.equals("全部")) {
                    for (int i = 0; i < filterChipGroup.getChildCount(); i++) {
                        Chip allChip = (Chip) filterChipGroup.getChildAt(i);
                        if (allChip.getText().equals("全部")) {
                            allChip.setChecked(false);
                            break;
                        }
                    }
                }
                
                // 应用过滤
                filterRewardTasks();
            });
            
            filterChipGroup.addView(chip);
        }
    }
    
    private void loadRewardTasks() {
        swipeRefreshLayout.setRefreshing(true);
        
        // 从MockDataManager获取所有悬赏任务
        List<RewardTask> rewardTasks = mockDataManager.getAllRewardTasks();
        
        // 过滤出未被接取的任务
        allRewardTasks.clear();
        for (RewardTask task : rewardTasks) {
            if (!task.isTaken()) {
                allRewardTasks.add(task);
            }
        }
        
        // 应用过滤
        filterRewardTasks();
        
        swipeRefreshLayout.setRefreshing(false);
    }
    
    private void filterRewardTasks() {
        String query = searchEditText.getText().toString().toLowerCase().trim();
        List<String> selectedCategories = new ArrayList<>();
        
        // 获取选中的类别
        for (int i = 0; i < filterChipGroup.getChildCount(); i++) {
            Chip chip = (Chip) filterChipGroup.getChildAt(i);
            if (chip.isChecked()) {
                selectedCategories.add(chip.getText().toString());
            }
        }
        
        // 检查是否选择了"全部"类别
        boolean includeAll = selectedCategories.contains("全部");
        
        // 过滤任务
        filteredRewardTasks.clear();
        for (RewardTask task : allRewardTasks) {
            // 先检查标题或描述是否包含搜索关键字
            boolean matchesQuery = query.isEmpty() ||
                    task.getTitle().toLowerCase().contains(query) ||
                    task.getDescription().toLowerCase().contains(query);
            
            // 再检查类别过滤条件
            boolean matchesCategory = includeAll;
            
            if (!includeAll) {
                String taskCategory = task.getCategory();
                for (String category : selectedCategories) {
                    if (taskCategory.equals(category)) {
                        matchesCategory = true;
                        break;
                    }
                }
            }
            
            if (matchesQuery && matchesCategory) {
                filteredRewardTasks.add(task);
            }
        }
        
        // 更新UI
        updateUI();
    }
    
    private void updateUI() {
        if (adapter != null) {
            adapter.updateData(filteredRewardTasks);
        }
        
        // 显示或隐藏空视图
        if (filteredRewardTasks.isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }
    
    public void refreshData() {
        if (isAdded()) {
            loadRewardTasks();
        }
    }

    @Override
    public void onRewardClick(RewardTask rewardTask) {
        // 打开悬赏详情页
        startActivity(RewardDetailActivity.createIntent(requireContext(), rewardTask.getId()));
    }

    @Override
    public void onTakeRewardClick(RewardTask rewardTask) {
        // 接取悬赏任务逻辑
        boolean success = mockDataManager.takeRewardTask(
                mockDataManager.getCurrentUsername(), 
                rewardTask.getId());
        
        if (success) {
            // 刷新数据
            loadRewardTasks();
        }
    }
} 